
MACRO ReadByte
	ldy #0
	lda (ACK_InputData),y
	inc ACK_InputData
	bne +	
	inc ACK_InputData+1	; if y wrapped to 0 we increase the high byte of the ptr
+
	ENDM 

MACRO SlideWindow
	; Expects X = bit count to slide into the window

-	dec LoadedBitsLeft	; decrease nr of loaded bits
	bpl ++

	ReadByte	
	sta LoadedByte
	lda #7
	sta LoadedBitsLeft
		
++	lsr LoadedByte		; one bit from LoadedByte -> ByteWindow
	ror Window		; new bit into ByteWindow
	dex
	bne -	
ENDM


MACRO ReadSymbol
	lda Window
	tay			; save A

	ldx #15
-	
;	REPT 8
	tya			; restore A
	and CodeMasks,x		; mask out the code bits
	cmp Codes,x		; did we find it?
	beq fnd
	dex
;	ENDR
	bpl -

	; Bad. We didn't find it! What to dooo?

fnd ; found
	txa
	pha

	; Advance sliding window X number of bits
	lda CodeLengths,x
	tax
	SlideWindow

	pla			; A = symbol

ENDM

Huffman_Init:

	ReadByte
	sta BankCount

	ReadByte
        sta BankSize
	ReadByte
	sta BankSize+1

	; InputStream is assumed to be at the start of a huffman block.

	ReadByte
;	sta ExpectedSymbolCount
	ReadByte
;	sta ExpectedSymbolCount+1

	; Codes (16 bytes)
	i = 0
	REPT 16
	ReadByte
	sta Codes+i
	i = i + 1
	ENDR

	; Code masks (16 bytes)
	i = 0
	REPT 16
	ReadByte
	sta CodeMasks+i
	i = i + 1
	ENDR

	; Code lengths (16 bytes)
	i = 0
	REPT 16
	ReadByte
	sta CodeLengths+i
	i = i + 1
	ENDR


	; Feed 8 bits into the sliding window.
	lda #0
	sta LoadedBitsLeft
	ldx #8
	SlideWindow

	rts

Huffman_ReadByte:
;	txa
;	pha
;	tya
;	pha

	ReadSymbol		; Read first symbol
	sta SymbolTemp	
	ReadSymbol		; Read second symbol
	asl			; Shift it up, it's the high nibble.
	asl
	asl
	asl
	ora SymbolTemp		; Combine the symbols into a byte.
	sta SymbolTemp

;	pla
;	tay
;	pla
;	tax	

	lda SymbolTemp
	rts



